<template>
  <div>
    <vxe-grid ref='xGrid' v-bind="gridOptions">
      <!-- 自定义显示模板 -->
      <template #exist_default="{ row }">
        <el-tag v-if="row.exist == 1" type="success">是 </el-tag>
        <el-tag v-else-if="row.exist == 0" type="danger"> 否 </el-tag>
      </template>

      <!-- 入库时间 查询模板 -->
      <template #rksj_default>
        <div class="block">
          <el-date-picker
            v-model="rksj_datePicker"
            @change="setTime"
            style="width:482px"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            :size="default"
          />
        </div>
      </template>
    </vxe-grid>
  </div>


</template>



<script setup name="Index" lang="ts">
  import commons from '@/common/config.js';
  import { onMounted, reactive, ref, computed,getCurrentInstance  } from 'vue'
  import { useStore } from 'vuex'
  import { VXETable, VxeGridInstance, VxeGridProps } from 'vxe-table'
  import XEUtils from 'xe-utils'
  import { listRk, rkUpDateBatch,rkInsertBatch,rkDeleteBatch,rkImport,rkExport,setTuozhuai,getTuozhuai } from "@/api/ck/rk";
  import Sortable from 'sortablejs'
  import {toJSON,toHTML,capitalize} from '@/utils/htmlZjson'
  import $ from 'jquery'

          const store = useStore()
          const serveApiUrl = "localhost:8080"
          const rkList = ref([]);
          const total = ref(0);
          const rksj_datePicker = ref([]);
          //快速时间选择
          const shortcuts = [
            {
              text: '七天内',
              value: () => {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                return [start, end]
              },
            },
            {
              text: '一个月内',
              value: () => {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                return [start, end]
              },
            },
            {
              text: '三个月内',
              value: () => {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
                return [start, end]
              },
            },
          ]

          

            const xGrid = ref<VxeGridInstance>()
            const label = commons.app.body.label.name
            const search = commons.app.body.label.search
            const reset = commons.app.body.label.reset
            const save = commons.app.body.button.save
            const gridOptions = reactive<VxeGridProps>({
              border: true,/*  */
              showFooter: true,
              class: 'sortable-column-demo',
              scrollX: {
                enabled: false
              },
              showHeaderOverflow: true,
              showOverflow: true,
              keepSource: true,
              id: 'full_edit_1',
              height: 800,
              rowConfig: {
                keyField: 'id',
                isHover: true
              },
              columnConfig: {
                useKey: true,
                resizable: true
              },
              customConfig: {
                storage: true,
                checkMethod ({ column }) {
                  if (['id'].includes(column.field)) {
                    return false
                  }
                  return true
                }
              },
              printConfig: {
                columns: [
                  { field: 'name' }
                ]
              },
              sortConfig: {
                trigger: 'cell',
                remote: true
              },
              filterConfig: {
                remote: true
              },
              pagerConfig: {
                pageSize: 10,
                pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000]
              },
              formConfig: {
                titleWidth: 100,
                titleAlign: 'right',
                items: [
                  { field: 'name', title: label, span: 8, titlePrefix: { message: '物品名称', icon: 'vxe-icon-question-circle-fill' }, itemRender: { name: '$input', props: { placeholder: '请输入名称' } } },
                  { 
                    field: 'rksj', title: '入库时间', span: 8, 
                    slots: { default: 'rksj_default'}
                  },
                  { field: 'xh', title: '型号', span: 8,folding: true,  titlePrefix: { useHTML: true, message: '点击链接：<a class="link" href="https://vxetable.cn" target="_blank">vxe-table官网</a>', icon: 'vxe-icon-question-circle-fill' }, itemRender: { name: '$input', props: { placeholder: '请输入邮件' } } },
                  { field: 'sn', title: '序列号', span: 8, folding: true, itemRender: { name: '$input', props: { placeholder: '请输入序列号' } } },
                  { field: 'pp', title: '品牌', span: 8, itemRender: { name: '$input', props: { placeholder: '请输入品牌' } } },
                  { field: 'exist', title: '是否在库', span: 8, folding: true, titleSuffix: { message: '注意，必填信息！', icon: 'vxe-icon-question-circle-fill' }, itemRender: { name: '$select', options: [] } },
                  { span: 24, align: 'center', collapseNode: true, itemRender: { name: '$buttons', children: [{ props: { type: 'submit', content: search, status: 'primary' } }, { props: { type: 'reset', content: reset } }] } }
                ]
              },
              toolbarConfig: {
                custom: true,
                buttons: [
                  { code: 'insert_actived', name: '新增' },
                  { code: 'delete', name: '直接删除',status: 'danger' },
                  { code: 'mark_cancel', name: '删除/取消' },
                  { code: 'save', name: save, status: 'success' }
                ],
                refresh: true,
                import: true,
                export: true,
                print: true,
                zoom: true
              },
              proxyConfig: {
                seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
                sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
                filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
                form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
                // 对应响应结果 { result: [], page: { total: 100 } }
                props: {
                  result: 'rows', // 配置响应结果列表字段
                  total: 'total' // 配置响应结果总页数字段
                },
                // 只接收Promise，具体实现自由发挥
                ajax: {
                  // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
                   query: async ({ page, sorts, filters, form }) => {
                    const queryParams = Object.assign({}, form)
                    // 处理排序条件
                    const firstSort = sorts[0]
                    if (firstSort) {
                      queryParams.sort = firstSort.field
                      queryParams.order = firstSort.order

                    }
                    // 处理筛选条件
                    filters.forEach(({ field, values }) => {
                      queryParams[field] = values.join(',')
                    }) 
                    const obj = {}
                    queryParams.pageNum =  page.currentPage
                    queryParams.pageSize = page.pageSize
                    const arr =  JSON.parse(JSON.stringify(rksj_datePicker.value))

                    queryParams.rksj_datePicker_q = date2String("YYYY-mm-dd",arr[0])
                    console.log("aaaa",typeof new Date(arr[0]))
                    queryParams.rksj_datePicker_j = date2String("YYYY-mm-dd",arr[1])
                    const response = await listRk(queryParams)
                    return response
                  },
                  // 当点击工具栏删除按钮或者手动提交指令 delete 时会被触发
                  delete: ({ body }) => {
                    const delIndexs = []
                    for(let i=0;i < body.removeRecords.length;i++ ){
                        delIndexs.push(body.removeRecords[i].id)
                    }
                    return rkDeleteBatch(delIndexs)
                  },
                  // 当点击工具栏保存按钮或者手动提交指令 save 时会被触发
                  save: async ({ body }) => {
                    const czData = JSON.stringify(body)
                    const insertRecords = body.insertRecords
                    const updateRecords = JSON.stringify(body.updateRecords)
                    if(updateRecords != "[]"){
                      rkUpDateBatch(updateRecords)
                    }
                    if(JSON.stringify(insertRecords) != "[]"){
                      for(let i=0;i < insertRecords.length;i++ ){
                        insertRecords[i].id = null
                      }
                      rkInsertBatch(JSON.stringify(insertRecords))
                   }
                    return await listRk()
                  }
                }
                      },
              columns: [
                { type: 'checkbox', title: '序号', width: 120,field:'id'},
                { field: 'name', title: '名称', sortable: true, titlePrefix: { message: '名称必须填写！' }, editRender: { name: 'input', attrs: { placeholder: '请输入名称' } } },
/*                 {
                  field: 'role',
                  title: 'Role',
                  sortable: true,
                  titlePrefix: { useHTML: true, content: '点击链接：<a class="link" href="https://vxetable.cn" target="_blank">vxe-table官网</a>' },
                  filters: [
                    { label: '前端开发', value: '前端' },
                    { label: '后端开发', value: '后端' },
                    { label: '测试', value: '测试' },
                    { label: '程序员鼓励师', value: '程序员鼓励师' }
                  ],
                  filterMultiple: false,
                  editRender: { name: 'input', attrs: { placeholder: '请输入角色' } }
                }, */
                { field: 'xh', title: '型号', width: 160, editRender: { name: '$input', props: { placeholder: '请输入邮件' } } },
                { field: 'pp', title: '品牌',align:'left',headerAlign:'center', editRender: { name: 'input', attrs: { placeholder: '请输入昵称' } } },
                {
                  field: 'exist',
                  title: '是否在库',
                  align:'center',
                  filters: [
                    { label: '是', value: '1' },
                    { label: '否', value: '0' }
                  ],
                  slots: {
                    // 使用插槽模板渲染
                    default: 'exist_default'
/*                     header: 'num1_header',
                    footer: 'num1_footer',
                    filter: 'num1_filter',
                    edit: 'num1_edit' */
                  },
                  editRender: { name: '$select', options: [], props: { placeholder: '请选择性别' } }
                },
                { field: 'sn', title: '序列号', visible: false, sortable: true, editRender: { name: '$input'/* , props: { type: 'number', min: 1, max: 120 }  */} },
                {
                  field: 'rksj',
                  title: '入库时间',
                  width: 160,
                  visible: false,
                  sortable: true,
                  formatter ({ cellValue }) {
                    return XEUtils.toDateString(cellValue, 'yyyy-MM-dd HH:ss:mm')
                  }
                },
                {
                  field: 'rkr',
                  title: '入库人',
                  width: 160,
                  visible: false,
                  sortable: true,
                  formatter ({ cellValue }) {
                    return XEUtils.toDateString(cellValue, 'yyyy-MM-dd')
                  }
                }
              ],
              importConfig: {
                remote: true,
                types: ['xlsx'],
                modes: ['insert','covering'],
                // 自定义服务端导入
                importMethod ({ file,options}) {
                  const $grid = xGrid.value
                  const formBody = new FormData()
                  formBody.append('file', file)
                  return rkImport(formBody,options.mode).then(response => {
                    VXETable.modal.message({ content: `成功导入 ${response.data.insertRows} 条记录！`, status: 'success' })
                    // 导入完成，刷新表格
                    $grid.commitProxy('query')
                  }).catch(() => {
                    VXETable.modal.message({ content: '导入失败，请检查数据是否正确！', status: 'error' })
                  })
                }
              },
              exportConfig: {
                remote: true,
                types: ['xlsx'],
                modes: ['current', 'selected', 'all'],
                // 自定义服务端导出
                exportMethod ({ options }) {
                  const $grid = xGrid.value
                  const proxyInfo = $grid.getProxyInfo()
                  const fieldsArr = []
                  options.columns.map((column) => {
                    fieldsArr.push(column.field)
                        //title: column.title
                    })

                  // 传给服务端的参数
                  const body = {
                    filename: options.filename,
                    sheetName: options.sheetName,
                    isHeader: options.isHeader,
                    original: options.original,
                    mode: options.mode,
                    pager: proxyInfo ? proxyInfo.pager : null,
/*                     pageNum: proxyInfo.pager.currentPage,
                    pageSize: proxyInfo.pager.pageSize, */
                    ids: options.mode === 'selected' ? options.data.map((item) => item.id) : [],
                    fields: fieldsArr,
                    rk: proxyInfo.form ? proxyInfo.form : null
                  }
                  // 开始服务端导出
                  return rkExport(body).then(response => {
                    response.data.imgUrl
                    if (response.data.imgUrl) {
                      VXETable.modal.message({ content: '导出成功，开始下载', status: 'success' })
                      // 读取路径，请求文件
                      fetch(response.data.imgUrl).then(response => {
                        response.blob().then(blob => {
                          // 开始下载
                          VXETable.saveFile({ filename: options.filename?options.filename:"入库数据导出", type: 'xlsx', content: blob })
                        })
                      })
                    }

                  }).catch(() => {
                    VXETable.modal.message({ content: '导出失败！', status: 'error' })
                  })
                }
              },
              checkboxConfig: {
                labelField: 'id',
                reserve: true,
                highlight: true,
                range: true
              },
              editRules: {
                name: [
                  { required: true, message: 'app.body.valid.rName' },
                  { min: 3, max: 50, message: '名称长度在 3 到 50 个字符' }
                ],
                email: [
                  { required: true, message: '邮件必须填写' }
                ],
                role: [
                  { required: true, message: '角色必须填写' }
                ]
              },
              editConfig: {
                trigger: 'click',
                mode: 'row',
                showStatus: true
              }
            })

            onMounted(() => {
              const existList = [
                { label: '否', value: '0' },
                { label: '是', value: '1' }
              ]
              const { formConfig, columns } = gridOptions
              if (columns) {
                const existColumn = columns[4]
                if (existColumn && existColumn.editRender) {
                  existColumn.editRender.options = existList
                }
              }
              if (formConfig && formConfig.items) {
                const existItem = formConfig.items[5]
                if (existItem && existItem.itemRender) {
                  existItem.itemRender.options = existList
                }
              }
            })

                /** 查询渠道列表 */
    function getList() {
        listRk().then(response => {
          rkList.value = response.rows;
        });
    }

    let sortable2 = null;
    const instance = getCurrentInstance()
              const _this= instance.appContext.config.globalProperties
        const columnDrop2 = () => {
              const $grid = xGrid.value

              sortable2 = Sortable.create($grid.$el.querySelector('.body--wrapper>.vxe-table--header .vxe-header--row'), {
                handle: '.vxe-header--column',
                 onEnd: (sortableEvent) => {           
                  const targetThElem = sortableEvent.item
                  const newIndex = sortableEvent.newIndex
                  const oldIndex = sortableEvent.oldIndex
                  const { fullColumn, tableColumn } = $grid.getTableColumn()
                  const wrapperElem = targetThElem.parentNode
                  const newColumn = fullColumn[newIndex]
                  if (newColumn.fixed) {
                    // 错误的移动
                    const oldThElem = wrapperElem.children[oldIndex]
                    if (newIndex > oldIndex) {
                      wrapperElem.insertBefore(targetThElem, oldThElem)
                    } else {
                      wrapperElem.insertBefore(targetThElem, oldThElem ? oldThElem.nextElementSibling : oldThElem)
                    }
                    VXETable.modal.message({ content: '固定列不允许拖动！', status: 'error' })
                    return
                  }
                  // 获取列索引 columnIndex > fullColumn
                  const oldColumnIndex = $grid.getColumnIndex(tableColumn[oldIndex])
                  const newColumnIndex = $grid.getColumnIndex(tableColumn[newIndex])
                  //把排好队序放入session
                  //let arr = JSON.parse(sessionStorage.getItem("rkSort"))

                  getTuozhuai().then(result =>{
                    let arr = result.data
                    
                    if(arr == null){
                    arr = [0,1,2,3,4,5,6,7]
                    }
                    //原数组删掉
                    const oldV =arr.splice(oldColumnIndex, 1)[0]
                    arr.splice(newColumnIndex,0,oldV)
                  // sessionStorage.setItem("rkSort",JSON.stringify(arr))
                   
                    setTuozhuai(arr)
                    // 移动到目标列
                    const currRow = fullColumn.splice(oldColumnIndex, 1)[0]
                    fullColumn.splice(newColumnIndex, 0, currRow)
                    $grid.loadColumn(fullColumn)
                  })
                }
              })
            }

            let initTime
            nextTick(() => {
              // 加载完成之后在绑定拖动事件
              initTime = setTimeout(() => {
                columnDrop2()
                hhSwaps()
              }, 100)
            })

            onUnmounted(() => {
              clearTimeout(initTime)
              columnDrop2()
              if (sortable2) {
                sortable2.destroy()
              }
            })

/*             //替换class值
            function tihuanClass(){
              const sortable = JSON.parse(sessionStorage.getItem('rkSort'))
              const aaa = new DOMParser().parseFromString(sortable, "text/xml");
              if(sortable){
                const aa = $('.vxe-table--header .vxe-header--row')
                $(aa).html(sortable)
              }

            }


      // 获取排序后的结果，并存入sessionStorage
      function sortList(nDom,lists) {
        const arr = []
        const oldclass = $(nDom).children();
        sessionStorage.setItem("rkSort",JSON.stringify($(nDom).html()))
        } */

      function customEvent(oldIndex,newIndex) {
        const $grid = xGrid.value
        const { fullColumn, tableColumn } = $grid.getTableColumn()              
        //const arr = JSON.parse(sessionStorage.getItem("rkSort"))
 /*        getTuozhuai("gaowms_rk_tuozhuai").then(response =>{

        }) */
        // 移动到目标列
        const currRow = fullColumn.splice(oldIndex, 1)[0]
        fullColumn.splice(newIndex, 0, currRow)
        $grid.loadColumn(fullColumn)
        }

        //根据session的拖拽排序 重排  [0, 2, 3, 4, 5, 6, 1, 7] arrOld aaaa arrNew bbbb
        async function hhSwaps() {
          const arrOld = [0,1,2,3,4,5,6,7]
          //const arrNew = JSON.parse(sessionStorage.getItem("rkSort"))
          const arrdata = await getTuozhuai()
          const arrNew = arrdata.data
          if(arrNew != null){
            for(let i = 0;i < arrNew.length; i++){
              for(let j=i;j < arrNew.length; j++){
                if( arrNew[i] == arrOld[i]){
                  break
                }
                if(arrNew[i] == arrOld[j]){
                  customEvent(j,i)
                  //按照sortablejs的规则排序数组
                  const old = arrOld.splice(j, 1)[0]
                  arrOld.splice(i, 0, old)
                }
              }

            }
          }
        }


        function festivalMethod ( {date} ) {
          const dateMaps = {
            20230121: {
              important: true, // 是否标记为重要节日
              label: '建军节', // 显示节日名称
              extra: {
                label: '休' // 右上角额外显示的事件名称
              }
            },
            20230122: {
              notice: true // 显示小圆点事件通知
            },
            20230123: {
              important: true,
              label: '国庆节,中秋节', // 如果同一天拥有多个节日重叠，用逗号分开
              extra: {
                important: true, // 是否标记为重要事件
                label: '班'
              }
            }
          }
          const ymd = XEUtils.toDateString(date, 'yyyyMMdd')
          return dateMaps[ymd] || { label: '无' }
        }

        /**
       * date 格式转yyyy-MM-dd HH:mm
       * dateFormat("YYYY-mm-dd HH:MM:SS", date)
       */
      function date2String(fmt, dateString) {

        const date = new Date(dateString);

        let ret;
        const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
        };
        for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
          fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
        };
        return fmt;
      }

</script>

<style scoped lang="scss">

</style>

